package com.hps.boot.shiro.config;

import com.hps.boot.shiro.auth.ShiroAuthFilter;
import com.hps.boot.shiro.auth.UserRealm;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author heps
 * @since 2020/6/9 17:32
 */
@Configuration
public class ShiroConfig {

  @Bean
  public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    bean.setSecurityManager(securityManager);

    Map<String, Filter> filterMap = new HashMap<>(4);
    filterMap.put("authFilter", new ShiroAuthFilter());
    bean.setFilters(filterMap);

    Map<String, String> map = new HashMap<>();
    map.put("/api/**", "authFilter");
    map.put("/user/login", "anon");
    bean.setFilterChainDefinitionMap(map);
    return bean;
  }

  @Bean
  public DefaultWebSecurityManager securityManager(UserRealm userRealm) {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(userRealm);
    return securityManager;
  }

  @Bean
  public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
    authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
    return authorizationAttributeSourceAdvisor;
  }

  @Bean
  public UserRealm userRealm() {
    return new UserRealm();
  }
}
